#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include "PackageParse.hpp"
#include "log.hpp"
#include "connection.hpp"

class IOserverce
{
public:
    IOserverce(func_t func)
        : _func(func)
    {
    }
    void HandlerRecv(Connection *conn)
    {

        Log(DEBUG, "recv from fd:%d", conn->SockFd());
        while (true)
        {
                char buffer[1024];
                ssize_t n = recv(conn->SockFd(), buffer, sizeof(buffer) - 1, 0);
                std::cout<<conn->SockFd()<<std::endl;
                if (n > 0)
                {
                    buffer[n] = '\0';
                    conn->AppendInbuffer(buffer);
                }
                else
                {
                    if (errno == EWOULDBLOCK || errno == EAGAIN)
                    {
                        break;
                    }
                    else if (errno == EINTR)
                    {
                        continue;
                    }
                    else
                    {
                        conn->_excepeter(conn);
                        return;
                    }
                }
                // 对读取的信息进行分析看是否读到了一个完整的请求
                _func(conn);
        }
    }

    void HandlerSend(Connection *conn)
    {
    }

    void HandlerExcept(Connection *conn)
    {
    }

private:
    func_t _func;
};